package com.sztz.interceptor;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.sztz.constants.CommonConstants;
import org.slf4j.MDC;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 日志拦截器，MDC添加跟踪ID
 * @author yzy
 * @date 2022/12/8 13:44
 */
public class LogInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String tid = IdUtil.simpleUUID();
        //如果请求头有传，就用请求头里的，否则用自已生成的UUID
        if(StrUtil.isNotBlank(request.getHeader(CommonConstants.TRACE_ID))){
            tid = request.getHeader(CommonConstants.TRACE_ID);
        }
        MDC.put(CommonConstants.TRACE_ID,tid);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        MDC.remove(CommonConstants.TRACE_ID);
    }
}
